<?php
/**
 * @copyright	Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die;

jimport('joomla.application.component.model');

/**
 * This models supports retrieving lists of article categories.
 *
 * @package		Joomla.Site
 * @subpackage	com_content
 * @since		1.6
 */
class ContentModelCategories_Home extends JModel
{
	/**
	 * The category context (allows other extensions to derived from this model).
	 *
	 * @var		string
	 */
	protected $_extension = 'com_content';
	
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @since	1.6
	 */
	protected function populateState()
	{
		$app = JFactory::getApplication();
		$this->setState('filter.extension', $this->_extension);
	
		// Get the parent id if defined.
		$parentId = JRequest::getInt('id');
		$this->setState('filter.parentId', $parentId);
	
		$params = $app->getParams();
		$this->setState('params', $params);
	
		$this->setState('filter.published',	1);
		$this->setState('filter.access',	true);
	}
	
	public function getItems()
	{
		$db = JFactory::getDbo();
		
		$query = $db->getQuery(true);
		
		$nullDate = $db->Quote($db->getNullDate());
		$nowDate = $db->Quote(JFactory::getDate()->toSQL());
		
		//get categories first
		$query->select('*')
				->from('#__categories c')
				->where('c.published = 1')
				->where('c.featured = 1')
				->where('extension = ' . $db->quote($this->_extension));
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		
		foreach ($rs as & $cat)
		{
			$query = $db->getQuery(true);
			
			$query->select('*')
					->from('#__content a')
					->where('a.state = 1')
					->where('a.catid = ' . (int) $cat->id)
					->order('a.ordering DESC')
					->where('(a.publish_up = ' . $nullDate . ' OR a.publish_up <= ' . $nowDate . ')')
					->where('(a.publish_down = ' . $nullDate . ' OR a.publish_down >= ' . $nowDate . ')')
					;
			
			$db->setQuery($query, 0, 4);
			$cat->articles = $db->loadObjectList();			
			
		}
		
		return $rs;
	}
}
